// ajax拦截加请求头token
async function addAjaxHesders() {
  // $.ajaxSetup({
  //   beforeSend: function (request) {
  //     request.setRequestHeader('access_token', access_token)
  //   },
  // })
  const access_token = localStorage.getItem('access_token')
  if (access_token) {
    const data = await auth('access_token', access_token)
    if (data.code == '0') {
      $.ajaxPrefilter(function (options) {
        if (!options.beforeSend) {
          options.beforeSend = function (request) {
            request.setRequestHeader('access_token', access_token)
          }
        }
      })
      return null
    } else if (data.code == '400' && data.result.name == 'TokenExpiredError') {
      const refresh_token = localStorage.getItem('refresh_token')
      const info = await auth('refresh_token', refresh_token)
      if (info.code == '0') {
        localStorage.setItem('access_token', info.result)
        $.ajaxPrefilter(function (options) {
          if (!options.beforeSend) {
            options.beforeSend = function (request) {
              request.setRequestHeader('refresh_token', info.result)
            }
          }
        })
        return null
      } else {
        alert('登录过期,请重新登录!')
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        const usertype = '0'
        // 根据权限渲染导航栏
        tabUser(usertype, '')
        changeNavbar(usertype)
      }
    }
  }
}

//根据角色渲染导航栏
async function changeDom() {
  const access_token = localStorage.getItem('access_token')
  const refresh_token = localStorage.getItem('refresh_token')

  if (!access_token) {
    const usertype = '0'
    // 根据权限渲染导航栏
    tabUser(usertype, '')
    changeNavbar(usertype)
    return null
  }
  try {
    const data = await auth('access_token', access_token)
    console.log('access_token:  ' + data.message)
    //判断access_token是否过期
    if (data.code == '0') {
      const decode = decodeTypeandName(access_token)
      //console.log(decode)
      const username = decode[0]
      const usertype = decode[1]
      user_id = decode[2]
      tabUser(usertype, username)
      changeNavbar(usertype)
      return null
    }
    if (data.code == '400' && data.result.name == 'TokenExpiredError') {
      const info = await auth('refresh_token', refresh_token)
      console.log('refresh_token:  ' + info.message)
      if (info.code == '0') {
        localStorage.setItem('access_token', info.result)
        const decode = decodeTypeandName(refresh_token)
        const username = decode[0]
        const usertype = decode[1]
        user_id = decode[2]
        tabUser(usertype, username)
        changeNavbar(usertype)
        return null
      } else {
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        const usertype = '0'
        tabUser(usertype, '')
        changeNavbar(usertype)
      }
    }
  } catch (error) {
    console.log(error)
  }
}

// 验证token是否有效
function auth(name, token) {
  return new Promise((resolve, reject) => {
    $.ajax({
      type: 'PUT',
      url: 'http://localhost:3000/auth', // 获取自己系统后台用户信息接口
      beforeSend: function (request) {
        request.setRequestHeader(name, token)
      },
      success: function (data) {
        resolve(data)
      },
      error: function (data) {
        reject(data)
      },
    })
  })
}

// 根据权限渲染导航栏
function changeNavbar(usertype) {
  userType = usertype
  if (usertype === 'admin') {
    //0-admin，
    $('#report').hide()
    $('#traffic').show()
    $('#vedio').show()
    $('#addEvent').show()
    $('#queryEvent').show()
    $('#updateEvent').show()
    $('#announce').show()
    $('#viewAnnce').show()
    $('#trafficInfo').show()
    $('#usermenu').prepend(`<li><a href="#" id="userManager">用户管理</a></li>`)
    $('#toolBox').show()
  } else if (usertype === 'traffic') {
    $('#report').hide()
    $('#traffic').show()
    $('#vedio').show()
    $('#addEvent').show()
    $('#queryEvent').show()
    $('#updateEvent').show()
    $('#announce').show()
    $('#viewAnnce').hide()
    $('#trafficInfo').show()
    $('#userManager').hide()
    $('#toolBox').show()
    $('#docLayerTreeBtn').show()
  } else if (usertype === 'all') {
    $('#report').show()
    $('#traffic').show()
    $('#vedio').hide()
    $('#addEvent').hide()
    $('#queryEvent').hide()
    $('#updateEvent').hide()
    $('#announce').hide()
    $('#viewAnnce').show()
    $('#trafficInfo').hide()
    $('#userManager').hide()
    $('#toolBox').show()
    $('#docLayerTreeBtn').hide()
  } else {
    $('#report').hide()
    $('#traffic').hide()
    $('#vedio').hide()
    $('#addEvent').hide()
    $('#queryEvent').hide()
    $('#updateEvent').hide()
    $('#announce').hide()
    $('#viewAnnce').show()
    $('#trafficInfo').hide()
    $('#userManager').hide()
    $('#toolBox').hide()
    $('#docLayerTreeBtn').hide()
  }
}

// 显示用户信息切换
function tabUser(usertype, username) {
  console.log(usertype)
  if (usertype == '0' || usertype == '') {
    //$('#user').text('登录')
    $('#user').html('登录<span class="caret"></span>')
    $('#usermenu li').remove()
    $('#usermenu').append(`<li><a  id="reg">注册</a></li>`)
  } else {
    $('#user').html(
      `<span class="glyphicon glyphicon-user" aria-hidden="true"></span>${username}<span class="caret"></span>`
    )
    //$('#user').text(username)
    $('#usermenu li').remove()
    $('#usermenu').append(`<li><a href="#" id="changePsw">修改密码</a></li>
    <li><a href="" id="logout">退出登录</a></li>`)
    report_user = username
  }
}

// 鼠标盘旋自动下拉
function dropdownOpen() {
  $('.dropdown')
    .mouseover(function () {
      $(this).addClass('show')
      //查找当前元素子节点中的对象，修改其class，这样
      //这样当有多个下拉菜单时，可以分别独立处理，而不会出现都下拉的bug
      $(this).find('.dropdown-menu').addClass('show')
    })
    .mouseout(function () {
      $(this).find('.dropdown-menu').removeClass('show')
      $(this).removeClass('show')
    })
}
// 登录
function loginClick() {
  $('body').on('click', '#user', function () {
    if ($('#user').text() === '登录') {
      window.location.replace('./login/login.html')
    }
  })
}

// 注册
function regClick() {
  $('body').on('click', '#reg', function () {
    window.location.replace('./login/login.html')
  })
}

//退出登录
function logoutClick() {
  $('body').on('click', '#logout', function () {
    const username = $('#user').text()
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    const usertype = '0'
    changeNavbar(usertype)
    tabUser(usertype, '')

    $.ajax({
      url: 'http://localhost:3000/users/logout/' + username,
      dataType: 'json',
      traditional: true, //属性在这里设置
      method: 'put',
      success: function (data) {
        if (data.code == '0') {
          alert('退出成功')
        } else {
          alert(data.result + '退出失败')
        }
      },
      error: function () {
        alert('退出失败')
      },
    })
  })
}

// 解密用户名类型
function decodeTypeandName(token) {
  const preload = token.split('.')[1]
  const decode = JSON.parse(
    CryptoJS.enc.Base64.parse(preload).toString(CryptoJS.enc.Utf8)
  )
  return [decode.name, decode.type, decode.sub]
}
